package com.taomeng.servlet.admin;

import com.taomeng.constant.MessageConstant;
import com.taomeng.entity.*;
import com.taomeng.service.LeaveService;
import com.taomeng.servlet.BaseServlet;
import com.taomeng.util.DateUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@WebServlet("/leave/*")
public class LeaveServlet extends BaseServlet {
    @Autowired
    private LeaveService leaveService;

    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int page = Integer.parseInt(req.getParameter("page"));
        int limit = Integer.parseInt(req.getParameter("limit"));
        String status = req.getParameter("status");

        PageBean<LeaveApplicationInfo> pageBean = leaveService.findAllByPage(page, limit, status);

        RespBody respBody = new RespBody();
        if (null != pageBean) {
            respBody.setCode(0);
            respBody.setMsg(MessageConstant.QUERY_SUCCESSFUL);
            respBody.setData(pageBean.getList());
            respBody.setCount(pageBean.getTotal());
        } else {
            respBody.setCode(500);
            respBody.setMsg(MessageConstant.QUERY_FAILS);
        }
        RespBody.JsonObject(resp, respBody);
    }

    public void submit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //判断是销假还是请假的提交
        String act  = req.getParameter("act");
        System.out.println(act);
        if (null==act ){
            application(req, resp);
        }else {
            back(req,resp);
        }

    }

    private void back(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int applicationId = Integer.parseInt(req.getParameter("id"));
        boolean studentBack = leaveService.studentBack(applicationId);
        if (studentBack){
            resp.sendRedirect("/public/shiwu");
        }else {
            resp.getWriter().println("fail");
        }

    }

    private void application(HttpServletRequest req, HttpServletResponse resp) throws IllegalAccessException, InvocationTargetException, IOException {
        Map<String, String[]> map = req.getParameterMap();  //获取前端传过来的信息，封装为 LeaveApplication

        //因为前端传过来的是字符串，需要把时间起个别名再进行格式化为Date类型，防止出现异常
        Date beginTime = DateUtils.parse(map.get("beginTime1")[0], "yyyy-MM-dd HH:mm");
        Date endTime = DateUtils.parse(map.get("endTime1")[0], "yyyy-MM-dd HH:mm");
        LeaveApplication leaveApplication = new LeaveApplication();

        //封装为实体类
        BeanUtils.populate(leaveApplication, map);
        BeanUtils.setProperty(leaveApplication, "begintime", beginTime);
        BeanUtils.setProperty(leaveApplication, "endtime", endTime);

        boolean flag = leaveService.add(leaveApplication);

        if (flag) {
            resp.sendRedirect("/public/shiwu");
        } else {
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().println("插入失败");
        }
    }

    public void detail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        List<LeaveApplicationDetail> detailList = leaveService.findDetailByApplicationId(id);

        RespBody respBody = new RespBody();
        respBody.setCode(200);
        respBody.setMsg("查找详情成功");
        respBody.setCount((long) detailList.size());
        respBody.setData(detailList);

        RespBody.JsonObject(resp, respBody);
    }

    public void audit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int id = Integer.parseInt(req.getParameter("id"));  //请假的id
        String opinion = req.getParameter("opinion");
        int result = Integer.parseInt(req.getParameter("result"));              //审批意见：（1：同意，2：不同意）

        //获取当前操作的用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();

        Integer status = leaveService.audit(id, user.getId(), opinion, result);

        RespBody respBody = new RespBody();
        ArrayList<Integer> list = new ArrayList<>();
        if (null != status) {
            list.add(status);
            respBody.setCode(200);
            respBody.setMsg(MessageConstant.DEAL_SUCCESSFUL);
            respBody.setData(list);
        } else {
            respBody.setCode(500);
            respBody.setMsg(MessageConstant.DEAL_FAILS);
        }
        RespBody.JsonObject(resp, respBody);

    }

    @Override
    public void init() throws ServletException {
        super.init();
        ServletContext application = this.getServletContext();
        // 解决servlet用@Autowired自动注入service失败的问题
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, application);
    }
}
